<template>
	<view>
		<view class="userinfo">
		        <button v-if="!hasUserInfo" open-type="getUserInfo" @tap="getUserInfo"> 登录 </button>
		        <block v-else>
		            <image class="userinfo-avatar" :src="userInfo.avatarUrl" mode="cover"></image>
		        </block>
		</view>
		<view class="usermotto">
			<form @submit="formSubmit">
				<text class="user-motto">昵称：</text>
				<view class="box nick-view">
					<input name="nikeName" :value="userInfo.nickName" disabled="true" class="unInput"></input>
				</view>
				<text class="user-motto">口令：</text>
				<view class="box">
					<input name="password"password class="weui-input" auto-focus maxlength="10" placeholder="请输入口令" />
				</view>
				<text class="user-motto">教师姓名：</text>
				<view class="box">
					<input name="name" class="weui-input" maxlength="10" placeholder="请输入教师姓名" />
				</view>
				<text class="user-motto">学生姓名：</text>
				<view class="box">
					<input name="stu_name" class="weui-input" maxlength="10" placeholder="请输入学生姓名" />
				</view>
				<!-- <text class="user-motto">工号：</text>
				<view class="box">
					<input name="id" class="weui-input" maxlength="10" placeholder="请输入工号" />
				</view> -->
	
				<text class="user-motto">年级：</text>

				<gradepicker name="stu_grade":value="gradeValue" @change='bindGradeChange'>
					{{gradeValue}}
				</gradepicker>
				<text class="user-motto">学科：</text>
					<picker @change="bindSbjChange" name="subject" :value="sbj_array[sbj_index]" :range="sbj_array">
						<view class="box unInput">
							{{sbj_array[sbj_index]}}
						</view>
					</picker>
				<text class="user-motto">请假情况：</text>
				<view class="box">
					<input name="leave" class="weui-input" maxlength="10" placeholder='如果请假, 请写请假二字' />
				</view>
				<text class="user-motto">授课开始时间：</text>
					<picker mode="time"id="start_time" name="start_time" start="06:00" end="21:00" :value="start_time" @change="bindTimeChange">
						<view class="box unInput">
							{{start_time}}
						</view>
					</picker>
				<text class="user-motto">授课结束时间：</text>
					<picker mode="time" id="end_time" name="end_time" start="07:00" end="22:00" :value="end_time" @change="bindTimeChange">
						<view class="box unInput">
							{{end_time}}
						</view>
					</picker>
				<text class="user-motto">本次授课时长：</text>
				<view class="box">
					<input name="this_time_length" class="weui-input" type="number" placeholder="请输入本次授课小时数" />
				</view>
				<text class="user-motto">本月第几次授课：</text>
				<view class="box">
					<input name="times_the_mon" class="weui-input" type="number" placeholder="请输入这次是本月第几次授课" />
				</view>
				<text class="user-motto">教学反馈：</text>
				<textarea name="feedback"class="box"></textarea>
				<text class="user-motto">位置名称：</text>
				<view >
					<block v-if="hasLocation === false">
						<text class="loca-text unInput">请点选地点后再确定</text>
					</block>
					<block v-if="hasLocation === true">
						<input name="locaAdd" :value="locationAddress" disabled="true" class="loca-text">{{locationAddress}}</input>
					</block>
				</view>
				<button type="default" @tap="chooseLocation" hover-class="other-button-hover"> 获取位置 </button>
	
				<text class="user-motto">位置坐标：</text>
				<view >
					<input class="unInput" disabled="true" name="locatude" :value="location ? ('经: '+location.longitude[0]+'°'+location.longitude[1]+'    纬:'+location.latitude[0]+'°'+location.latitude[1]) : '请先获取位置'"> </input>
				</view>
				<text hidden class="user-motto">设备坐标：</text>
				<view hidden>
					<input class="unInput" disabled="true" name="dev_locatude" :value="dev_location ? ('经: '+dev_location.longitude[0]+'°'+dev_location.longitude[1]+'    纬:'+dev_location.latitude[0]+'°'+dev_location.latitude[1]) : '请先获取位置'"></input>
				</view>
	
				<text class="user-motto">照片:</text>
				<view class="box">
					<image class="liv-pic" :src="imageList" mode="aspectFit"></image>
					<view class="weui-uploader__input-box">
						<button type="default" class="weui-uploader__input" hover-class="other-button-hover" @tap="chooseImage">拍照或相册</button>
					</view>
				</view>
	
				<button type="primary" :size="defaultSize" :loading="loading" :plain="plain" :disabled="disabled" form-type="submit" hover-class="other-button-hover"> 提交 </button>
			</form>
		</view>
	</view>
</template>

<script>
	const app = getApp()
	import gradepicker from '../../components/edu-picker/grade-picker.vue'
	export default {
		components:{
			gradepicker
		},
		data() {

			return {
				gradeValue:'请选择年级',
				userInfo: {
					nickName: "昵称未获取，请先获取昵称",
					stu_grade:''
				},
				location: null,
				locationAddress: null,
				hasLocation: false,
				hasUserInfo: false,
				imageList: null,
				sbj_array: app.globalData.subjectList.map(item=>item.name),
				sbj_index: 0,
				start_time:'00:00',
				end_time:"00:00"
			}
		},

		onLoad: function () {
			if (app.globalData.hasUserInfo) {
				//如果app之前已经获取UserInfo，则直接写入
				this.setData({
					userInfo: app.globalData.userInfo,
					hasUserInfo: true
				})
			} else {
				uni.showToast({
					title:'请先登录',
					icon:'error'
				})
			} 
		},
	
		methods: {
			setData(newData){
				Object.keys(newData).forEach(k=>{
					this[k] = newData[k]
				})
			},
			bindTimeChange: function(e) {
				console.log('picker发送选择改变，携带值为', e.detail.value)
				this.setData({
				  time: e.detail.value
				})
			},
			
			bindSbjChange(e){
				this.setData({sbj_index:e.detail.value})
			},
			
			bindGradeChange : function(e) {
				console.log('picker发送选择确认，携带值为', e)
				this.gradeValue = e.value
			},
			  
		  //点击获取昵称时，获取用户信息，在得到用户信息时回调
		    getUserInfo: function (e) {
				if(app.globalData.hasUserInfo)
					return 
				wx.getUserProfile({
					desc: '用于打卡登录',
					success: res => {
					  // 可以将 res 发送给后台解码出 unionId
					app.globalData.userInfo = res.userInfo
					console.log('wx.getUserProfile',res)
					
					this.hasUserInfo = app.globalData.hasUserInfo = true;
					this.userInfo = res.userInfo;
					},
					fail: result=>{
						console.log(result)
						if (result.errMsg === 'getUserProfile:fail auth deny') {
							uni.showModal({
								title: '获取用户信息失败',
								content: '错误原因:您点击了拒绝',
								showCancel: false
							});
							return;
						}
					}
				})
				
		    },
		  //选择图片
			chooseImage() {
			  const that = this //使用常量代替当前页面
			  wx.chooseImage({ //json中直接使用this指json对象
				  sourceType: ['camera', 'album'],
				  sizeType: ['compressed'],
				  count: 1,
				  success(res) {
					  console.log(res)
					  that.setData({
						  imageList: res.tempFilePaths
					  })
				  }
			  })
			},
			      //选择位置
		    chooseLocation() {
			  //要求用户先登陆才能选择位置
			  if (app.globalData.hasUserInfo) {
				  const that = this
				  //用户自选地点
				  wx.chooseLocation({
					  success: res => {
						  console.log(res)
						  //防止未获取到地名
						  if (res.name != '') {
							  that.setData({
								  hasLocation: true,
								  //记录选择地点的经纬度
								  location: this.formatLocation(res.longitude, res.latitude),
								  //记录选择地点的地名
								  locationAddress: res.name
							  })
						  }else {
							  that.setData({
								  hasLocation: true,
								  //记录选择地点的经纬度
								  location: this.formatLocation(res.longitude, res.latitude),
								  //记录选择地点的地名
								  locationAddress: "未知地点"
							  })
						  }
					  }
				  })
				  //获取设备的经纬度
				  wx.getLocation({
					  success: res => {
						  console.log(res)
						  that.setData({
							  dev_location: this.formatLocation(res.longitude, res.latitude)
						  })
					  },
					  fail(e) {
						  that.setData({
							  hasLocation: false
						  })
						  console.error('设备经纬度获取失败', e)
						  wx.showToast({
							  title: '获取位置失败，请检查是否开启位置信息',
							  icon: 'none',
						  })
					  }
				  })
				  wx.showToast({
					  title: '请稍等',
					  icon: 'loading',
				  })
			  } else {
				  wx.showModal({
					  title: '请先登录',
					  content: '',
	  
				  })
			  }
		  },
		  //当表格提交
			formSubmit: function (e) {
			  console.log('form发生了submit事件，携带数据为：', e)
			  //把表格中的数据写入data
			  this.setData({
				  ev: e.detail.value
			  })
			  const that = this
			  if (this.ev.password != app.globalData.key){
				  wx.showModal({
					  title: '口令输入错误！',
				  })
			  } else if (this.hasLocation) {
				  if (this.dev_location.longitude[1]==this.location.longitude[1]
					  && this.dev_location.latitude[1]==this.location.latitude[1]){
					  wx.showModal({
						  title: '您的位置信息有误',
						  content: '请重新选择准确的位置信息后再提交',
					  })
				  } else if (this.imageList)
					  wx.showModal({
						  title: '确定提交吗？',
						  content: '请确认无误后再提交',
						  success: function (res) {
							  if (res.confirm) {
								  that.doDBsave(that)
							  }
						  }
					  })
				  else {
					  wx.showModal({
						  title: '您还未选择打卡图片',
						  content: '确定要提交打卡信息么？',
						  confirmText: '提交',
						  cancelText: '取消',
						  success: function (res) {
							  if (res.confirm) {
								  that.doDBsave(that)
							  }
						  }
					  })
				  }
			  } else {
				  wx.showModal({
					  title: '请先获取位置信息'
				  })
			  }
			},
			formatTime(date) {
			  const year = date.getFullYear()
			  const month = date.getMonth() + 1
			  const day = date.getDate()
			  // const hour = date.getHours()
			  // const minute = date.getMinutes()
			  // const second = date.getSeconds()
			
			  return [year, month, day].map(n => {
				  n = n.toString()
				  return n[1] ? n : '0' + n
				}).join('-')
			  //  + ' ' + [hour, minute, second].map(formatNumber).join(':')
			},
				//微信云开发的数据库储存
			doDBsave(that) {
				let nowDate = new Date()
				const v = that.ev
				const db = wx.cloud.database()
				db.collection('daka_records').add({
					data: {...v,
						date:this.formatTime(nowDate),
						stu_grade:this.gradeValue
					},
					success: res => {
						// 在返回结果中会包含新创建的记录的 _id
						wx.showToast({
							title: '新增记录成功',
						})
						console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
						//数据库操作成功后开始上传图片
						if (that.imageList.length > 0){
			
							let cloudPath = 'dakaPhotos/'+this.formatTime(nowDate)+'_'+res._id+'.png'
							this.doUpload(that.imageList[0],cloudPath)
							db.collection('daka_records').doc(res._id).update({
								data:{
									photoUrl:app.globalData.photoHttpsUrlHead + cloudPath
								}
							}) 
						}
					},
					fail: err => {
						wx.showToast({
							icon: 'none',
							title: '新增记录失败'
						})
						console.error('[数据库] [新增记录] 失败：', err)
					}
				})
			},
			// 上传图片
			doUpload(filePath,cloudPath) {
				console.log('cloudPath', cloudPath)
				wx.showLoading({
					title: '上传中',
				})
				// 上传图片
				
				wx.cloud.uploadFile({
					cloudPath,
					filePath,
					success: res => {
						console.log('[上传文件] 成功：', res)
						wx.showModal({
							title: '上传成功！',
							content: '',
							success(res) {
								wx.navigateBack()
							}
						})
						this.fileID = res.fileID
						this.cloudPath = cloudPath
						this.imagePath = filePath
			
					},
					fail: e => {
						console.error('[上传文件] 失败：', e)
						wx.showToast({
							icon: 'none',
							title: '上传失败',
						})
					},
					complete: () => {
						wx.hideLoading()
					}
				})
			
			},
			//经纬度格式调整
			formatLocation(longitude, latitude) {
				if (typeof longitude === 'string' && typeof latitude === 'string') {
					longitude = parseFloat(longitude)
					latitude = parseFloat(latitude)
				}
				//保留几位小数
				longitude = longitude.toFixed(4)
				latitude = latitude.toFixed(4)
			
				return {
					longitude: longitude.toString().split('.'),
					latitude: latitude.toString().split('.')
				}
			}
		}
	}
</script>

<style>
.userinfo {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.userinfo-avatar {
  width: 128rpx;
  height: 128rpx;
  margin: 20rpx;
  border-radius: 50%;
}

.unInput {
  color: #999;
}

.usermotto {
  /* margin-top: 100px; */
  width: 90%;
  margin: 0 auto;

}
.box{
  border: 1rpx solid black;
  border-radius: 10rpx;

}
.nick-view{
  border: none
}
.liv-pic{
}
.loca-text{
}
</style>
